#include "registerdialog.h"
#include "ui_registerdialog.h"
#include <textinput.h>
#include <QIcon>
#include <QComboBox>
#include <QDebug>
#include <QtSql/QSqlDatabase>
#include <QMessageBox>
#include <QtSql/QSqlError>
#include <QSqlQuery>
#include <QStringList>
#include <db.h>
#include <emp_mainwindow.h>
#include <QTimer>
#include <QPushButton>
#include <databasetask.h>
#include <QThreadPool>

RegisterDialog::RegisterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);

    /* 窗口标题和图片 */
    this->setWindowTitle("智慧医疗管理系统");
    QPixmap pixmap;
    pixmap.load(":/images/TitleIcon.png");
    QIcon icon;
    icon.addPixmap(pixmap);
    this->setWindowIcon(icon);
    /* 窗口标题和图片 */

    ui->labelTitle->setLabelName("智慧医疗系统注册");
    ui->labelTitle->showLabelName();

    createCombox();
    createTextInput();
    createButton();

    db = DB::getInstance();
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
    delete buttot_1;
    delete buttot_2;
    delete comboBox;
    delete roleLabel;
    delete db; // 销毁 DB 类实例
}

void RegisterDialog::initializeInterface()
{
    this->exec();
}
void RegisterDialog::createButton()
{
    buttot_1 = new QPushButton();
    buttot_2 = new QPushButton();

    buttot_1->setText("登录");
    buttot_2->setText("注册");

    buttonLayout = new QHBoxLayout(ui->buttonWidget);
    buttonLayout->addStretch();
    buttonLayout->addWidget(buttot_1);
    buttonLayout->addWidget(buttot_2);
    buttonLayout->addStretch();

    connect(buttot_2,&QPushButton::clicked,this,&RegisterDialog::RegisterUser);
    connect(buttot_1,&QPushButton::clicked,
            [=]()
    {
        this->close();
    });
}

void RegisterDialog::createTextInput()
{
    ui->textInput_1->setLabelName("身份证");
    ui->textInput_1->setPlaceholderText("请输入身份证号");
    ui->textInput_1->setTextInputModel("Normal");
    ui->textInput_1->showTextInput();

    ui->textInput_2->setLabelName("密码");
    ui->textInput_2->setPlaceholderText("请输入密码");
    ui->textInput_2->setTextInputModel("Password");
    ui->textInput_2->showTextInput();
}

void RegisterDialog::createCombox()
{
    // 创建 QComboBox 对象
    comboBox = new QComboBox(ui->role);
    // 添加选项
    comboBox->addItem("患者");
    comboBox->addItem("医生");
    comboBox->addItem("管理员");
    roleLabel = new QLabel(ui->role);
    roleLabel->setText("角色选择");
    roleLayout = new QHBoxLayout(ui->role);
    roleLayout->addStretch();
    roleLayout->addWidget(roleLabel);
    roleLayout->addWidget(comboBox);
    roleLayout->addStretch();
}
void RegisterDialog::RegisterUser()
{
    this->role = this->comboBox->currentText();
    this->username = ui->textInput_1->getTextInput();
    this->password = ui->textInput_2->getTextInput();
    if(this->role != "患者")
    {
        QMessageBox::information(this, "警告", "权限不足!无法注册!");
        return;
    }
    if(ui->textInput_1->getTextInput().size() == 0)
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确身份证号");
        return;
    }
    if(ui->textInput_2->getTextInput().size() == 0)
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确密码");
        return;
    }
    if(!isValidIDNumber(username))
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确身份证号");
        return;
    }
    if(!isValidPassword(password) || this->password.size()<8)
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确密码八位以上包含字母数字");
        return;
    }

    // Usage
    QString quires = QString("INSERT INTO tms (tms_gg, tms_user, tms_password) "
                    "VALUES (:tms_gg, :tms_user, :tms_password)");
    QVariantMap params = {
        {"tms_gg", role},
        {"tms_user", username},
        {"tms_password", password}
    };

    DatabaseTask* task = new DatabaseTask(quires, params, "注册");
    connect(task, &DatabaseTask::finished, this, &RegisterDialog::handleResults);
    connect(task, &DatabaseTask::error, this, &RegisterDialog::handleError);
    QThreadPool::globalInstance()->start(task);

}

// 身份证号码正则表达式
bool RegisterDialog::isValidIDNumber(const QString &username)
{
    QRegularExpression regex("^\\d{17}[0-9Xx]$");
    QRegularExpressionMatch match = regex.match(username);
    return match.hasMatch();
}

// 简单密码验证:是否包含数字和字母
bool RegisterDialog::isValidPassword(const QString &password)
{
    bool hasNumber = false;
    bool hasLetter = false;

    for (QChar c : password)
    {
        if (c.isDigit())hasNumber = true;
        else if (c.isLetter())
            hasLetter = true;

        if (hasNumber && hasLetter)
            return true;
    }

    return false;
}
void RegisterDialog::handleResults(const QStringList& results)
{
    if(results.at(0) == "执行成功")
    {
        // 注册成功关闭当前窗口
        QMessageBox::information(this, "注册结果", "注册成功");
        // 清空文本框内容
        ui->textInput_1->clear();
        ui->textInput_2->clear();
        // 关闭窗口
        this->close();
    }
}

void RegisterDialog::handleError(const QString& errorMessage)
{
    qDebug() << "Database error:" << errorMessage;
    QMessageBox::information(this, "注册结果", "注册失败,该账号已存在");
}
